package tools

//参考博客；gorm与logrus 的连接 https://www.cnblogs.com/taoshihan/p/13846256.html
//gin 与 logrus 的配置  https://blog.csdn.net/XinLiangTalk/article/details/96942157?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.nonecase
//gorm的文档 https://jasperxu.com/
import (
	"fmt"
	"os"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

//定义gin的日志输出函数
func LoggerToFile() gin.HandlerFunc {
	//读取配置，获取输出日志信息
	loggerFilePATH := viper.GetString("Config.logfilePATH")
	loggerFileNAME := viper.GetString("config.gin-logfileName")
	//日志文件
	fileName := path.Join(loggerFilePATH, loggerFileNAME)
	//写入文件
	src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if err != nil {
		fmt.Println("err", err)
	}
	//实例化
	logger := logrus.New()
	//设置输出
	logger.Out = src
	//设置日志级别
	logger.SetLevel(logrus.DebugLevel)
	//设置日志格式
	logger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})
	return func(c *gin.Context) {
		//开始时间
		startTime := time.Now()
		//处理请求
		c.Next()
		//结束时间
		endTime := time.Now()
		//执行时间
		latencyTime := endTime.Sub(startTime)
		//请求方式
		requMethod := c.Request.Method
		//请求路由
		reqUri := c.Request.RequestURI
		//状态码
		statusCode := c.Writer.Status()
		//请求IP
		clientIP := c.ClientIP()
		//日志格式
		logger.WithFields(logrus.Fields{
			"status_code":  statusCode,
			"latency_time": latencyTime,
			"client_ip":    clientIP,
			"req_method":   requMethod,
			"req_url":      reqUri,
		}).Info()
	}
}

//定义mysql的日志输出函数
func Mysql_logger() *logrus.Logger {
	loggerFilePATH := viper.GetString("Config.logfilePATH")
	loggerFileNAME := viper.GetString("Config.mysql-logfileName")
	fileName := path.Join(loggerFilePATH, loggerFileNAME)
	src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if err != nil {
		fmt.Println("err", err)
	}

	logger := logrus.New()

	logger.Out = src

	logger.SetLevel(logrus.DebugLevel)

	logger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	return logger
}
